"""
Case Type   : 系统内部使用工具
Case Name   : 执行初始化数据库命令gs_ctl init：系统默认区域的编码格式和用--encoding参数
Create At   : 2022-07-28
Owner       : liu-tong-8848
Description :
    1.执行gs_ctl init的命令
    2.查看初始化生成的目录
    3.查看编码格式
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import unittest
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
import os


class Tools(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.userNode = Node('PrimaryDbUser')
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.dir_path = os.path.join(macro.DB_INSTANCE_PATH, 'datadir')
        self.nodename = 'nodename_127'

    def test_systools(self):
        self.logger.info(f'-----{os.path.basename(__file__)}' + ' start-----')

        text = '--step1:执行gs_ctl init的命令；expect：成功--'
        self.logger.info(text)
        excute_cmd1 = f'source {self.DB_ENV_PATH};' \
                      f'gs_ctl init -D {self.dir_path} -o ' \
                      f'"--nodename="{self.nodename}" -w ' \
                      f'"{self.userNode.ssh_password}" --locale=zh_CN.utf8 ' \
                      f'--encoding=UTF8"'
        self.logger.info(excute_cmd1)
        msg1 = self.userNode.sh(excute_cmd1).result()
        self.logger.info(msg1)
        self.assertIn('Success. You can now start the database server of '
                      'single node', msg1, text + '执行失败')

        text = '--step2:查看初始化生成的目录；expect：成功--'
        self.logger.info(text)
        excute_cmd2 = f'ls {self.dir_path}'
        self.logger.info(excute_cmd2)
        msg2 = self.userNode.sh(excute_cmd2).result()
        self.logger.info(msg2)
        self.assertIn('postgresql.conf' and 'pg_hba.conf', msg2, text + '执行失败')

        text = '--step3:查看编码格式；expect：成功--'
        self.logger.info(text)
        excute_cmd3 = f'locale|grep LC_CTYP'
        self.logger.info(excute_cmd3)
        msg3 = self.userNode.sh(excute_cmd3).result()
        self.logger.info(msg3)
        self.assertIn('en_US.UTF-8', msg3, text + '执行失败')

    def tearDown(self):
        text = '--step4:清理环境；expect：成功--'
        self.logger.info(text)
        excute_cmd4 = f'rm -rf {self.dir_path};ls {self.dir_path}'
        self.logger.info(excute_cmd4)
        msg4 = self.userNode.sh(excute_cmd4).result()
        self.logger.info(msg4)
        self.assertTrue(msg4.find('No such file or directory') > -1)
        self.logger.info(
            f'-----{os.path.basename(__file__)}' + ' end-----')
